<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="searchValue">
        <el-input
          v-model="queryParams.searchValue"
          placeholder="请输入名称/编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="物料编码" prop="code">-->
<!--        <el-input-->
<!--          v-model="queryParams.code"-->
<!--          placeholder="请输入物料编码"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料组编码" align="center" prop="code" />
      <el-table-column label="物料组名称" align="center" prop="name" />
      <el-table-column label="单位" align="center" prop="unit">
        <template #default="scope">
          <dict-tag :options="sys_unit" :value="scope.row.unit"/>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row, scope.index)" v-hasPermi="['business:product:query']">详细</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:product:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:product:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物料信息对话框 -->
    <el-dialog :title="title" v-model="open" width="800" append-to-body >
      <el-form ref="productRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物料组编码" prop="code">
          <el-input v-model="form.code" :disabled="editDis" placeholder="请输入物料组编码" />
        </el-form-item>
        <el-form-item label="物料组名称" prop="name" >
          <el-input v-model="form.name" :disabled="editDis" placeholder="请输入物料组名称" />
        </el-form-item>
        <el-form-item label="单位" prop="unit" >
          <el-select v-model="form.unit" filterable :disabled="editDis" placeholder="请选择单位">
            <el-option
                v-for="dict in sys_unit"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-divider content-position="center">物料规格信息</el-divider>
        <el-row :gutter="10" class="mb8" v-show="!editDis">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddProductSku">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteProductSku">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="productSkuList" :row-class-name="rowProductSkuIndex" @selection-change="handleProductSkuSelectionChange" ref="productSku">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="物料编码" prop="code" width="130">
            <template #default="scope">
              <el-input v-model="scope.row.code" :disabled="editDis" placeholder="请输入物料编码" />
            </template>
          </el-table-column>
          <el-table-column label="规格型号" prop="name" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.name" :disabled="editDis" placeholder="请输入规格型号" />
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="price" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.price" :disabled="editDis" placeholder="请输入单价" />
            </template>
          </el-table-column>
          <el-table-column label="安全库存" prop="safetyStock" width="130">
            <template #default="scope">
              <el-input v-model="scope.row.safetyStock" :disabled="editDis" placeholder="请输入安全库存" type="number" max="1000000"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-show="!editDis">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product">
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/business/product";

const { proxy } = getCurrentInstance();
const { sys_unit } = proxy.useDict('sys_unit');

const productList = ref([]);
const productSkuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedProductSku = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const editDis = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    searchValue: null,
    name: null,
    code: null
  },
  rules: {
    name: [
      { required: true, message: "物料名称不能为空", trigger: "blur" }
    ],
    unit: [
      { required: true, message: "单位不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建日期不能为空", trigger: "blur" }
    ],
    createBy: [
      { required: true, message: "创建人不能为空", trigger: "blur" }
    ],
    delFlag: [
      { required: true, message: "删除标志不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询物料信息列表 */
function getList() {
  loading.value = true;
  listProduct(queryParams.value).then(response => {
    productList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    unit: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    delFlag: null,
    code: null
  };
  productSkuList.value = [];
  proxy.resetForm("productRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
function handleView(row) {
  const _id = row.id || ids.value
  getProduct(_id).then(response => {
    form.value = response.data;
    productSkuList.value = response.data.productSkuList;
    open.value = true;
    title.value = "查看物料信息";
    editDis.value = true;
  });
}
/** 新增按钮操作 */
function handleAdd() {
  editDis.value = false;
  reset();
  open.value = true;
  title.value = "添加物料信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  editDis.value = false;
  const _id = row.id || ids.value
  getProduct(_id).then(response => {
    form.value = response.data;
    productSkuList.value = response.data.productSkuList;
    open.value = true;
    title.value = "修改物料信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      form.value.productSkuList = productSkuList.value;
      if (form.value.id != null) {
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除物料信息编号为"' + _ids + '"的数据项？').then(function() {
    return delProduct(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 物料规格属性序号 */
function rowProductSkuIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 物料规格属性添加按钮操作 */
function handleAddProductSku() {
  let obj = {};
  obj.name = "";
  obj.unit = "";
  obj.code = "";
  obj.price = "";
  obj.stock = "";
  obj.safetyStock = "";
  productSkuList.value.push(obj);
}

/** 物料规格属性删除按钮操作 */
function handleDeleteProductSku() {
  if (checkedProductSku.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的物料规格属性数据");
  } else {
    const productSkus = productSkuList.value;
    const checkedProductSkus = checkedProductSku.value;
    productSkuList.value = productSkus.filter(function(item) {
      return checkedProductSkus.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleProductSkuSelectionChange(selection) {
  checkedProductSku.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}

getList();
</script>
